<?php

// +----------------------------------------------------------------------
// | Admin Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2024 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-admin
// | github 代码仓库：https://github.com/zoujingli/think-plugs-admin
// +----------------------------------------------------------------------

declare(strict_types=1);

namespace app\dao\controller;

use app\api\model\DaoVipDetail;
use app\api\model\Userr;
use think\admin\Controller;
use think\admin\helper\QueryHelper;

/**
 * @class Dao
 * @package app\dao\controller
 */
class Dao extends Controller
{
    /**
     * 会员订单
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        DaoVipDetail::mQuery()->layTable(function () {
            $this->title = '会员订单';
            $this->pay_list = [
                [
                    'id' => 1,
                    'name' => '微信'
                ], [
                    'id' => 2,
                    'name' => '支付宝'
                ], [
                    'id' => 3,
                    'name' => 'PC后端'
                ], [
                    'id' => 4,
                    'name' => '苹果支付'
                ], [
                    'id' => 5,
                    'name' => 'PayPal支付'
                ]
            ];
            $this->is_pay_list = ['待支付', '已支付'];
        }, static function (QueryHelper $query) {
            $query->like('user_name')->dateBetween('pay_time')->equal('is_pay,pay_mode');
        });
    }

    /**
     * 用户管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function user()
    {
        $data = $this->request->get();
        Userr::mQuery()->layTable(function () {
            $this->title = '用户管理';
            $this->pay_list = [
                [
                    'id' => 1,
                    'name' => '微信'
                ], [
                    'id' => 2,
                    'name' => '支付宝'
                ], [
                    'id' => 3,
                    'name' => 'PC后端'
                ], [
                    'id' => 4,
                    'name' => '苹果支付'
                ]
            ];
            $this->is_pay_list = ['待支付', '已支付'];
        }, static function (QueryHelper $query) use ($data) {
            if (!empty($data['b5'])) {
                [$start_time, $end_time] = explode(' - ', $data['b5']);
                $start_time = strtotime($start_time);
                $end_time = strtotime($end_time);
                $query->whereRaw("b5>='$start_time' and b5<='$end_time'");
            }
            $query->like('zh');
        });
    }

    public function vipDelete()
    {
        $id = $this->request->get('id', '');
        if (empty($id)) $this->error('缺少必要参数');
        $bool = DaoVipDetail::mk()->where(['id' => $id])->delete();
        if ($bool === false) $this->error('记录删除失败!');
        $this->success('记录删除成功~');
    }

    /**
     * 列表数据处理
     * @param array $data
     * @throws \Exception
     */
    protected function _user_page_filter(array &$data)
    {
        foreach ($data as &$vo) {
            if (!empty($vo['b1']) && time() < strtotime($vo['b1'] . ' 23:59:59')) {
                $timestamp1 = strtotime($vo['a2']);
                $timestamp2 = strtotime($vo['b1']);
                $secondsDifference = abs($timestamp2 - $timestamp1);
                $vo['day_diff'] = floor($secondsDifference / (60 * 60 * 24));
            } else {
                $vo['day_diff'] = '';
            }

            $vo['b5'] = $vo['b5'] ? date('Y-m-d H:i:s', (int)$vo['b5']) : '';

        }
    }

    public function cancel()
    {
        $zh = $this->request->get('zh', '');
        if (empty($zh)) $this->error('缺少必要参数');
        $bool = Userr::mk()->where(['zh' => $zh])->update(
            [
                'vip' => '',
                'a2' => '',
                'b1' => ''
            ]
        );
        if (!$bool) $this->error('会员作废失败');
        $this->success('会员身份取消成功~');
    }

    public function delete()
    {
        $zh = $this->request->get('zh', '');
        if (empty($zh)) $this->error('缺少必要参数');
        $bool = Userr::mk()->where(['zh' => $zh])->delete();
        if ($bool === false) $this->error('用户删除失败!');
        $this->success('用户删除成功~');
    }


    public function record()
    {
        $zh = $this->request->get('zh', '');
        if (empty($zh)) $this->error('缺少必要参数');
        $user_info = Userr::mk()->where(['zh' => $zh])->findOrEmpty();
        $this->record_json = json_encode([]);
        if (!empty($user_info['system']) && $user_info['system'] != 'null') {
            $record_data = json_decode($user_info['system'], true);
            $new_record_data = [];
            $k = 0;
            foreach ($record_data as $key => $value) {
                $new_record_data[$k] = $value;
                $new_record_data[$k]['name'] = $key;
                $new_record_data[$k]['id'] = $k;
                $k++;
            }
            $this->record_json = json_encode($new_record_data);
        }
        $this->zh = $zh;
        $this->fetch();
    }

    /**
     * 添加用户
     * @auth true
     */
    public function customer()
    {
        $this->title = '添加用户';
        Userr::mForm('user_form');
    }

    /**
     * 添加用户
     * @auth true
     */
    public function edit()
    {
        $this->title = '编辑';
        Userr::mForm('edit_form');
    }

    /**
     * 添加用户表单处理
     * @param array $data
     */
    protected function _customer_form_filter(array &$data)
    {
        if ($this->request->isPost()) {
            $user_info = Userr::mk()->where(['zh' => $data['zh']])->find();
            if (!empty($user_info)) $this->error('该账号已存在!', 'javascript:location.reload()');
        }
    }

    /**
     * 添加会员
     * @auth true
     */
    public function add()
    {
        $this->title = '添加会员';
        $this->vip_list = config('pay.vip_list');
        Userr::mForm('form');
    }

    /**
     * 添加拼团商品表单处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            if (!empty($data['vip'])) {
                $config = config('pay');
                $this_vip = [];
                foreach ($config['vip_list'] as $vip) {
                    if ($vip['type'] == $data['vip']) $this_vip = $vip;
                }
                $user_info = Userr::mk()->where(['zh' => $data['zh']])->field('zh,a2,b1')->find();
                $days = $this_vip['month'] * 30;
                if (!empty($user_info['b1']) && time() < strtotime($user_info['b1'])) {
                    $user_start_time = $user_info['a2'];
                    $start_time = date('Y-m-d', strtotime($user_info['b1'] . ' +1 days'));
                } else {
                    $user_start_time = $start_time = date('Y-m-d');
                }
                $end_time = date('Y-m-d', strtotime($start_time . " +$days days"));
                $trade_sn = create_sn();
                $order_info = [
                    'user_name' => $data['zh'],
                    'vip_sn' => $trade_sn,
                    'buy_money' => $data['buy_money'],
                    'buy_time' => date('Y-m-d H:i:s'),
                    'pay_time' => date('Y-m-d H:i:s'),
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'type' => $data['vip'],
                    'desc' => "PC后台 {$this_vip['name']}添加",
                    'ip' => $this->app->request->ip(),
                    'pay_mode' => 3,
                    'is_pay' => 1,
                ];
                $bool = DaoVipDetail::mk()->insert($order_info);
                if (!$bool) $this->error('会员订单信息添加失败');
                $bool = Userr::mk()->where(['zh' => $data['zh']])->update(
                    [
                        'vip' => $data['vip'],
                        'a2' => $user_start_time,
                        'b1' => $end_time
                    ]
                );
                if (!$bool) $this->error('用户信息更新失败');
            }
        }
    }
}
